Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
How do I access the "checked" property of a HTML checkbox element using TypeScript?

I have the following HTML Code:

<input type="checkbox" id="check-one">

The following CSS code:

.check-one {
accent-color: #9d3039; }

And the following TypeScript code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  arrayName = new Array(10000);
}

const checkInput = document.getElementById('check-one') as HTMLInputElement;

console.log(checkInput.checked);

Whenever I view the console, all I get is an error that reads: Uncaught TypeError: checkInput is null

I'm wondering why this is happening? Why is it not returning either True or False since checkInput.checked is a boolean? Additionally, how to I manipulate this property so that the box can be checked and unchecked using a line of code in Typescript?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The element does not exist when you make your query because your code gets executed when importing that TS file. The template for this component has not yet been injected into the DOM.

You need to wait until after the view is initialized before querying the DOM. You can use the ngAfterViewInit hook for this:

export class AppComponent implements AfterViewInit {
  ngAfterViewInit() {
    const checkInput = document.getElementById('check-one') as HTMLInputElement;
    console.log(checkInput.checked);
  }
}

Docs for lifecycle hooks: https://angular.io/guide/lifecycle-hooks


In an angular project, you can use a template reference and the ViewChild decorator to select an HTML element:

<input type="checkbox" #checkOne />
export class AppComponent implements AfterViewInit {
  @ViewChild('checkOne') _checkOne?: ElementRef;
  get checkOne(): HTMLInputElement | undefined {
    return this._checkOne?.nativeElement;
  }

  ngAfterViewInit() {
    console.log(this.checkOne?.checked);
  }
}

This is safer since you know exactly which element is being selected and it's easier to make repetitive calls.


As for setting the value of checked it's pretty simple from there:

export class AppComponent implements AfterViewInit {
  @ViewChild('checkOne') _checkOne?: ElementRef;
  get checkOne(): HTMLInputElement | undefined {
    return this._checkOne?.nativeElement;
  }

  ngAfterViewInit() {
    if (this.checkOne) {
      console.log(this.checkOne.checked);
      this.checkOne.checked = true;
      console.log(this.checkOne.checked);
    }
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

you can use onChange attribute to trigger a action when checked

    <input type="checkbox" name="checkbox" value="<%=item._id%>" onChange="this.form.submit()">

and later you can use the name attribute to target the value attribute

about 4 years ago · Juan Pablo Isaza Relatório

0

I realy suggest to use:

<input type="checkbox" [(ngModel)]="check_box_value" />

to bind the property check_box_value to manipulate state on dom.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda